﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ToolBoxPro;
using LinqObj;
using System.Text;

public partial class forgotpassword : System.Web.UI.Page
{
    ToolboxDataContext tdc = new ToolboxDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
    {
        var user = from u in tdc.Toolbox_Users
                   where u.user_name == txt_user_name.Text
                   select u;
        if (user.Count() > 0)
        {
            StringBuilder randomstring = new StringBuilder();
            randomstring.Append(RandomNumber(1, 10000));
            randomstring.Append(RandomString(txt_user_name.Text.Length));
            randomstring.Append(RandomNumber(1, 10000));
            string body = "";
            body += "<table width='100%'>";
            body += "<tr><td>Hi,</td></tr><tr height='20'><br/><td></td></tr>";
            body += "<tr><td>Click on the link below to reset your password</td></tr>";
            body += "<tr><td><br/>http://testing.iplan3d.com.au/resetpassword.aspx?username="+ txt_user_name.Text +"&randomstring="+ randomstring +"</td></tr>";
            body += "<tr><td><br/> if you cannot click on the link above then copy and paste it into the browser.</td></tr>";
            body += "</table>";
            Notifications emailUser = new Notifications(user.Single().Email, "iplan3d - password reset", body);
            emailUser.SendEmail();
            user.Single().randomstring = randomstring.ToString();
            tdc.SubmitChanges();

            string script = "";
            script += "<script>";
            script += "alert('Please check your email.'); window.location.href = 'login.aspx';";
            script += "</script>";
            Page.RegisterStartupScript("script", script);
        }
        else
        {
            lblmsg.Visible = true;
        }

    }

    protected void btnBack_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("Login.aspx");
    }

    private string RandomString(int size)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;

        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }

        return builder.ToString();
    }


    private int RandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }
}